<script setup lang="ts">
import type { CustomDialogInstance, EquipmentDefinition } from '@/types'

import type { EfficiencyConfig, SaveEfficiencyParams } from '../type'
import { EFFICIENCY_ROLE_SYMBOL, EFFICIENCY_DATA_TYPE, EFFICIENCY_LOCATION } from '../constant'

import { STORAGE_MODES } from '@/enum/modules/indicator'

defineOptions({
  name: 'MiddleSettingPanel',
})

const props = defineProps<{
  attachmentDefinitions: EquipmentDefinition[]
  equipmentId: number | string
  oldList: EfficiencyConfig[]
}>()

const emit = defineEmits<{
  (e: 'open'): void
  (e: 'close'): void
  (e: 'saveSuccess'): void
}>()

const dialogRef = ref<CustomDialogInstance>()
const modalTitle = computed(() => {
  return `状态图设置`
})

const equipmentStore = useEquipmentStore()

const info = ref<{
  dataType: EFFICIENCY_DATA_TYPE
  dataValue: string
  timeType: STORAGE_MODES
  _timeTypeOptions: { label: string, value: string }[]
  roleList: {
    symbol: EFFICIENCY_ROLE_SYMBOL
    value: number | string
    showDefinitionInfoId: number | string
    _definitionInfoName: string
    _definitionInfoId: number | string
    _definitionInfoAttachment: {
      fileName: string
      fileUrl: string
    }
  }[]
}>({
  dataType: EFFICIENCY_DATA_TYPE.POINT,
  dataValue: '',
  timeType: STORAGE_MODES.NOW,
  _timeTypeOptions: [],
  roleList: [
    {
      symbol: EFFICIENCY_ROLE_SYMBOL.GT,
      value: '',
      showDefinitionInfoId: '',
      _definitionInfoId: '',
      _definitionInfoName: '',
      _definitionInfoAttachment: { fileName: '', fileUrl: '' },
    },
  ],
})

const indicatorList = computed(() => {
  return equipmentStore.indicatorList
})

async function clickSave(done: () => void) {
  const v = unref(info)
  const params: SaveEfficiencyParams = {
    equipmentId: +unref(props.equipmentId),
    location: EFFICIENCY_LOCATION.CENTER,
    list: [{
      equipmentId: +unref(props.equipmentId),
      location: EFFICIENCY_LOCATION.CENTER,
      dataValue: v.dataValue,
      dataType: v.dataType,
      timeType: v.timeType,
      roleList: v.roleList.map(({ _definitionInfoAttachment, _definitionInfoId, _definitionInfoName, ...rest }) => ({ ...rest })),
    }],
  }

  const isEmpty = (s: any) => s === '' || s === null || s === undefined

  if (isEmpty(v.dataType)) {
    done()
    return ElMessage.warning('请选择数据源类型')
  }
  if (isEmpty(v.dataValue)) {
    done()
    return ElMessage.warning('请输入点位或指标')
  }
  if (isEmpty(v.timeType)) {
    done()
    return ElMessage.warning('请选择数据周期')
  }
  if (v.roleList.some(vv => isEmpty(vv.value))) {
    done()
    return ElMessage.warning('请输入规则值')
  }
  try {
    await equipmentEfficiencyApi.saveEquipmentEfficiencyConfigData(params)
    ElMessage.success('保存成功')
    done()
    close()
    emit('saveSuccess')
  }
  finally {
    done()
  }
}

function handleChangeDataType() {
  info.value.dataValue = ''
  info.value.timeType = info.value.dataType === EFFICIENCY_DATA_TYPE.POINT
    ? STORAGE_MODES.NOW
    : (null as any)
}

function getPeriodName(type: STORAGE_MODES) {
  switch (type) {
    case STORAGE_MODES.DAY:
      return '日'
    case STORAGE_MODES.MONTH:
      return '月'
    case STORAGE_MODES.YEAR:
      return '年'
    case STORAGE_MODES.NOW:
      return '实时'
    case STORAGE_MODES.FIFTEEN_MINUTES:
      return '15分钟'
    case STORAGE_MODES.HOUR:
      return '小时'
    default:
      return ''
  }
}

function getPeriodListFromIndicator(indicatorNumber: string) {
  const indicator = unref(indicatorList).find(v => v.indicatorNumber === indicatorNumber)
  if (indicator) {
    const indicatorDataStoreCoreList = indicator?.indicatorDataStoreCoreList ?? []
    return indicatorDataStoreCoreList.map(v => ({
      label: getPeriodName(v.timeType),
      value: v.timeType,
    }))
  }
  return []
}

function handleChangeDataValue() {
  const indicator = unref(indicatorList).find(v => v.indicatorNumber === info.value.dataValue)
  const indicatorDataStoreCoreList = indicator?.indicatorDataStoreCoreList ?? []
  info.value._timeTypeOptions = indicatorDataStoreCoreList.map(v => ({
    label: getPeriodName(v.timeType),
    value: v.timeType,
  }))
  info.value.timeType = indicatorDataStoreCoreList[0].timeType
}

const loading = ref(false)
async function open() {
  dialogRef.value?.open()
  if (props.equipmentId) {
    try {
      loading.value = true
      await equipmentStore.getIndicatorList(props.equipmentId)
    }
    finally {
      loading.value = false
    }
  }
  emit('open')
}
async function close() {
  dialogRef.value?.close()
  emit('close')
}

watchEffect(() => {
  const old = unref(props.oldList)[0]
  const attachmentDefinitions = unref(props.attachmentDefinitions) ?? []
  if (old) {
    info.value = {
      dataType: old.dataType,
      dataValue: old.dataValue,
      timeType: old.timeType || STORAGE_MODES.NOW,
      _timeTypeOptions: getPeriodListFromIndicator(old.dataValue),
      roleList: old.roleList.length > 0
        ? old.roleList.map((v, i) => {
          const a = attachmentDefinitions[i] ?? {}
          const file = a.attachments?.[0]
          return {
            ...v,
            _definitionInfoId: a.id ?? 0,
            _definitionInfoName: a.name ?? '',
            _definitionInfoAttachment: {
              fileName: file?.fileName ?? '',
              fileUrl: file?.fileUrl ?? '',
            },
          }
        })
        : attachmentDefinitions.map((v) => {
          const file = v.attachments?.[0]
          return {
            symbol: EFFICIENCY_ROLE_SYMBOL.EQ,
            value: '',
            showDefinitionInfoId: v.id as string | number,
            _definitionInfoId: v.id ?? 0,
            _definitionInfoName: v.name ?? '',
            _definitionInfoAttachment: {
              fileName: file?.fileName ?? '',
              fileUrl: file?.fileUrl ?? '',
            },
          }
        }),
    }
  }
  else {
    info.value = {
      dataType: EFFICIENCY_DATA_TYPE.POINT,
      dataValue: '',
      timeType: STORAGE_MODES.NOW,
      _timeTypeOptions: [],
      roleList: attachmentDefinitions.map((v) => {
        const file = v.attachments?.[0]
        return {
          symbol: EFFICIENCY_ROLE_SYMBOL.EQ,
          value: '',
          showDefinitionInfoId: v.id as string | number,
          _definitionInfoId: v.id ?? 0,
          _definitionInfoName: v.name ?? '',
          _definitionInfoAttachment: {
            fileName: file?.fileName ?? '',
            fileUrl: file?.fileUrl ?? '',
          },
        }
      }),
    }
  }
})

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    :title="modalTitle"
    width="640px"
    need-saving
    @confirm="clickSave"
  >
    <div class="p-3">
      <div v-loading="loading" element-loading-custom-class="global-loading">
        <div class="flex-auto">
          <div class="flex items-center border-b border-gray-200 p-3">
            <span class="flex-shrink-0 opacity-80">数据源类型：</span>
            <ElRadioGroup v-model="info.dataType" class="flex-auto" @change="handleChangeDataType">
              <ElRadio label="点位" :value="EFFICIENCY_DATA_TYPE.POINT" />
              <ElRadio label="指标" :value="EFFICIENCY_DATA_TYPE.INDICATOR" />
            </ElRadioGroup>
          </div>
          <div v-if="info.dataType === EFFICIENCY_DATA_TYPE.POINT" class="flex items-center border-b border-gray-200 p-3">
            <span class="block w-20 flex-shrink-0 opacity-80">点位：</span>
            <ElInput v-model="info.dataValue" class="flex-auto" placeholder="请输入" />
          </div>
          <div v-else class="flex items-center border-b border-gray-200 p-3">
            <span class="block w-20 flex-shrink-0 opacity-80">指标：</span>
            <ElSelect v-model="info.dataValue" class="flex-auto" placeholder="请选择" @change="handleChangeDataValue">
              <ElOption v-for="item in indicatorList" :key="item.indicatorNumber" :value="item.indicatorNumber" :label="item.indicatorName" />
            </ElSelect>
          </div>
          <div class="flex items-center border-b border-gray-200 p-3">
            <span class="block w-20 flex-shrink-0 opacity-80">数据周期：</span>
            <ElSelect v-if="info.dataType === EFFICIENCY_DATA_TYPE.INDICATOR" v-model="info.timeType" class="flex-auto" placeholder="请选择">
              <ElOption v-for="item in info._timeTypeOptions" :key="item.value" v-bind="item" />
            </ElSelect>
            <ElSelect v-else v-model="info.timeType" class="flex-auto" disabled placeholder="请选择">
              <ElOption key="0m" label="实时" value="0m" />
            </ElSelect>
          </div>
        </div>
        <div v-for="(item, index) in info.roleList" :key="index" class="alpha-block mb-4 flex p-4">
          <span class="w-15 flex-shrink-0 opacity-80">{{ item._definitionInfoName }}</span>
          <img :src="item._definitionInfoAttachment.fileUrl" class="mx-3 h-20 w-20" object-fit="cover">
          <div class="flex-auto">
            <div class="flex items-center">
              <span class="mr-3 flex-shrink-0 opacity-80">数据</span>
              <ElRadioGroup v-model="item.symbol">
                <ElRadio label="大于" :value="EFFICIENCY_ROLE_SYMBOL.GT" />
                <ElRadio label="等于" :value="EFFICIENCY_ROLE_SYMBOL.EQ" />
                <ElRadio label="小于" :value="EFFICIENCY_ROLE_SYMBOL.LT" />
              </ElRadioGroup>
            </div>
            <div class="mt-2">
              <ElInput v-model="item.value" type="number" placeholder="请输入参考值" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </CustomDialog>
</template>

<style scopeds>
.required:before {
  content: '*';
  margin-right: 4px;
  color: rgb(254, 107, 107);
}
.chosenClass {
  border: solid 1px rgb(167, 20, 56);
}
</style>
